package com.ruoyi.stream.server;

import com.ruoyi.stream.framework.config.StreamServerConfig;
import com.ruoyi.stream.server.handler.SKARequestDecoder;
import com.ruoyi.stream.server.handler.SKAResponseEncoder;
import com.ruoyi.stream.server.handler.ServiceHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

@Component
public class NettyStreamServer implements ApplicationRunner {

    @Autowired
    private StreamServerConfig config;

    private void start() throws InterruptedException {
        ServerBootstrap serverBootstrap = new ServerBootstrap();
        serverBootstrap.channel(NioServerSocketChannel.class);
        EventLoopGroup boss = new NioEventLoopGroup(config.bossThreads);
        EventLoopGroup worker = new NioEventLoopGroup(config.workerThreads);
        serverBootstrap.group(boss,worker);
        serverBootstrap.childHandler(new ChannelInitializer<NioSocketChannel>() {
            @Override
            protected void initChannel(NioSocketChannel nioSocketChannel) throws Exception {
                ChannelPipeline pipeline = nioSocketChannel.pipeline();
                pipeline.addLast("baseCodec",new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE,8,8,0,0));
                pipeline.addLast("requestDecoder",new SKARequestDecoder());
                pipeline.addLast("responseEncoder",new SKAResponseEncoder());
                pipeline.addLast("service",new ServiceHandler());
            }
        });
        serverBootstrap.bind(config.port).sync();
        System.out.println(config.port);
    }

    @Override
    public void run(ApplicationArguments args) throws Exception {
        start();
        System.out.println("running");

    }
}
